package util

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	ResponseBodyKey = "response-body"

	MessageOK = "OK"
)

type (
	Response struct {
		Code    int         `json:"code"`
		Message string      `json:"message"`
		Payload interface{} `json:"payload"`
	}

	PaginationResp struct {
		Size  int         `json:"size"`
		Index int         `json:"page"`
		Data  interface{} `json:"data"`
		Total int         `json:"total"`
	}
)

func ResponseOK(ctx *gin.Context, payload interface{}) {
	ResponseJSON(ctx, http.StatusOK, payload)
}

func ResponseJSON(ctx *gin.Context, status int, payload interface{}) {
	buf, err := json.Marshal(payload)
	if err != nil {
		panic(err)
	}
	ctx.Set(ResponseBodyKey, buf)
	ctx.Data(status, "application/json; charset=utf-8", buf)
	ctx.Abort()
}

func OKWithPayload(payload interface{}) *Response {
	return &Response{
		Code:    http.StatusOK,
		Message: MessageOK,
		Payload: payload,
	}
}

func OK() *Response {
	return &Response{
		Code:    http.StatusOK,
		Message: MessageOK,
	}
}
